package com.lxh.cptp.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.lxh.cptp.tp.WxCpTpRedisConfigImpl;
import com.lxh.cptp.utils.HttpUtils;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.cp.api.WxCpTpService;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import org.apache.commons.lang3.StringUtils;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * created by lanxinghua@2dfire.com on 2020/2/24
 * 对第三方一些常用接口进行封装
 */
public class BaseController {
    public static Map<String/*企业Id*/, String/*永久授权码*/> authMap = Maps.newHashMap();
    public static Map<String/*商圈Id*/, String/*企业Id*/> testMap = Maps.newHashMap();
    static {
        authMap.put("wwd276de90ff82e1e3", "_D_NFuBRw1CPFWbXPYI2WSq7Z4TJe0a6hsBlDCocUlc");
        authMap.put("ww4007bc86bede5885", "WDy636gh8ZLndcfeCC3FKFdW-qzzqpOpAcyZPa7XuvE");

        testMap.put("000001", "wwd276de90ff82e1e3"); // 星火科技
        testMap.put("000002", "ww4007bc86bede5885"); // 2dfire
    }

    private static String getuserinfo3rdUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?suite_access_token=%s&code=%s";
    private static String getuserdetail3rdUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/getuserdetail3rd?suite_access_token=%s";

    /**
     * 获取用户信息
     * getSuiteAccessToken 缓存期2小时
     * @throws Exception
     */
    public static JSONObject getUserInfo3rd(WxCpTpService tpService, String code) throws Exception{
        JSONObject result = HttpUtils.sendGet(String.format(getuserinfo3rdUrl, tpService.getSuiteAccessToken(), code));
        System.out.println(result.toString());
        System.out.println("user_ticket：" + result.get("user_ticket"));
        return result;
    }


    /**
     * 获取访问用户敏感信息
     * @throws Exception
     */
    public static JSONObject getUserDetail3rd(WxCpTpService tpService, String user_ticket) throws Exception{
        JSONObject object = new JSONObject();
        object.put("user_ticket", user_ticket);
        JSONObject result = HttpUtils.sendPost(String.format(getuserdetail3rdUrl, tpService.getSuiteAccessToken()), object.toJSONString());
        System.out.println("用户详细信息："+result.toJSONString());
        return result;
    }


    /**
     * 获取企业的jsapi_ticket
     * 有效期为7200s
     * @return
     */
    public static JSONObject getJsApiTicket(String authCorpId, WxCpTpService tpService){
        WxCpTpConfigStorage wxCpTpConfigStorage = tpService.getWxCpTpConfigStorage();
        if (wxCpTpConfigStorage instanceof WxCpTpRedisConfigImpl){
            WxCpTpRedisConfigImpl cpTpRedisConfig = (WxCpTpRedisConfigImpl) wxCpTpConfigStorage;
            String jsApiTicket = cpTpRedisConfig.getJsApiTicket(authCorpId);
            if (StringUtils.isNoneEmpty(jsApiTicket)){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("ticket", jsApiTicket);
                return jsonObject;
            }
            try {
                WxAccessToken wxAccessToken = tpService.getCorpToken(authCorpId, authMap.get(authCorpId));
                JSONObject result = innerGetJsApiTicket(wxAccessToken.getAccessToken());
                System.out.println(result.toString());
                String ticket = result.getString("ticket");
                int expires = result.getInteger("expires_in");
                // 更新到缓存
                cpTpRedisConfig.updateJsApiTicket(ticket, expires, authCorpId);
                return result;
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            try {
                WxAccessToken wxAccessToken = tpService.getCorpToken(authCorpId, authMap.get(authCorpId));
                JSONObject result = innerGetJsApiTicket(wxAccessToken.getAccessToken());
                System.out.println(result.toString());
                return result;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }


    private static JSONObject innerGetJsApiTicket(String accessToken){
        try {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=%s";
            JSONObject result = HttpUtils.sendGet(String.format(url, accessToken));
            System.out.println(result.toString());
            System.out.println("ticket：" + result.get("ticket"));
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static Map<String, Object> getParameter(String url) {
        Map<String, Object> map = new HashMap<>();
        try {
            final String charset = "utf-8";
            url = URLDecoder.decode(url, charset);
            if (url.indexOf('?') != -1) {
                final String contents = url.substring(url.indexOf('?') + 1);
                String[] keyValues = contents.split("&");
                for (int i = 0; i < keyValues.length; i++) {
                    String key = keyValues[i].substring(0, keyValues[i].indexOf("="));
                    String value = keyValues[i].substring(keyValues[i].indexOf("=") + 1);
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    private static String getPreAuthCode(String suiteAccessToken){
        try {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=%s";
            JSONObject result = HttpUtils.sendGet(String.format(url, suiteAccessToken));
            System.out.println(result.toString());
            System.out.println("pre_auth_code：" + result.get("pre_auth_code"));
            return String.valueOf(result.get("pre_auth_code"));
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
